package servlet;

import utils.QRCodeUtil;
import service.ShareService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 生成分享二维码的Servlet
 */
@WebServlet(name = "qrcode", urlPatterns = "/qrcode")
public class QRCodeServlet extends HttpServlet {

    private ShareService shareService = new ShareService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取商品ID
        String goodsIdStr = request.getParameter("id");
        
        if (goodsIdStr == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "商品ID不能为空");
            return;
        }
        
        try {
            int goodsId = Integer.parseInt(goodsIdStr);
            
            // 获取当前应用的基础URL
            String baseUrl = getBaseUrl(request);
            
            // 生成分享链接
            String shareLink = QRCodeUtil.generateShareLink(goodsId, baseUrl);
            
            // 使用外部服务生成二维码图片
            String qrcodeUrl = QRCodeUtil.getQRCodeImageUrl(shareLink, 200);
            
            // 重定向到二维码图片URL
            response.sendRedirect(qrcodeUrl);
            
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "商品ID格式错误");
        }
    }
    
    /**
     * 获取应用的基础URL
     * @param request HTTP请求
     * @return 基础URL
     */
    private String getBaseUrl(HttpServletRequest request) {
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String contextPath = request.getContextPath();
        
        // 构建基础URL
        StringBuilder url = new StringBuilder();
        url.append(scheme).append("://").append(serverName);
        
        // 只有在非默认端口时才添加端口号
        if ((scheme.equals("http") && serverPort != 80) || 
            (scheme.equals("https") && serverPort != 443)) {
            url.append(":").append(serverPort);
        }
        
        url.append(contextPath);
        
        return url.toString();
    }
} 